package pro.softzhang.algo.lc0;

import pro.softzhang.algo.common.ListNode;
import pro.softzhang.algo.common.Utils;

/**
 *
 */
public class LC21_MergeTwoSortedLists {
    public static void main(String[] args) {
        ListNode l1 = new ListNode(1, new ListNode(2, new ListNode(4)));
        ListNode l2 = new ListNode(1, new ListNode(3, new ListNode(4)));
        Utils.printLinkedList(new Solution().mergeTwoLists(l1, l2));
    }

    static
    class Solution {
        public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
            ListNode dummy = new ListNode(), prev = dummy;
            while (list1 != null && list2 != null) {
                if(list1.val <= list2.val) {
                    prev.next = list1;
                    list1 = list1.next;
                } else {
                    prev.next = list2;
                    list2 = list2.next;
                }
                prev = prev.next;
            }
            prev.next = list1 == null ? list2 : list1;
            return dummy.next;
        }
    }
}
